package net.vkits.anjiamiao.domain.model;

import net.vkits.common.BaseModel;
import net.vkits.common.converters.LocalDateAttributeConverter;
import net.vkits.common.converters.LocalDateTimeAttributeConverter;
import net.vkits.common.validators.CellPhoneNum;
import org.hibernate.validator.constraints.NotEmpty;

import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Created by ethan-liu on 16/6/2.
 */
@Entity
@Table(name = "verify_code")
public class VerifyCode extends BaseModel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotEmpty
    @CellPhoneNum
    private String cellPhoneNum;
    @NotEmpty
    private String verifyCode;
    private int validTime;
    @Convert(converter = LocalDateAttributeConverter.class)
    private LocalDate sendDate;
    @Convert(converter = LocalDateTimeAttributeConverter.class)
    private LocalDateTime sendTime;
    private boolean used;

    public VerifyCode(String cellPhoneNum, String verifyCode, int validTime) {
        this.cellPhoneNum = cellPhoneNum;
        this.verifyCode = verifyCode;
        this.validTime = validTime;
        this.sendDate = LocalDate.now();
        this.sendTime = LocalDateTime.now();
        this.used = false;
    }

    public void use(){
        this.used = true;
    }

    public boolean isExpired() {
        LocalDateTime expiryDate = this.sendTime.plusMinutes(this.validTime);
        return  expiryDate.isBefore(LocalDateTime.now());
    }

    // just for JPA
    private VerifyCode() {
    }
}
